package com.usian.order.service.impl;

import com.usian.order.fegin.UserFegin;
import com.usian.order.mapper.OrderMapper;
import com.usian.order.pojo.Order;
import com.usian.order.pojo.User;
import com.usian.order.service.OrderService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 10 24 09 10
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;


    @Autowired
    UserFegin userFegin;


//    @Autowired
//    RestTemplate restTemplate;

    @Override
    public Order findOrderById(Integer id) {
        //{} 格式化;占位符
        log.info("要查询的订单ID：{}",id);

        Order order = orderMapper.findOrderById(id);
        log.info("查询出来的订单信息：{}",order.toString());
        Integer userId = order.getUserId();
        log.info("这个订单的userID：{}",userId);
        //通过userId 去调用user-service 查询用户信息
       // User user = restTemplate.getForObject("http://localhost:8070/user/findUserById?id=" + userId, User.class);

//        User user = restTemplate.getForObject("http://user-service/user/findUserById?id="+userId, User.class);
//
//        order.setUser(user);

    //    通过fegin去调用user-service 查询用户信息

        User user = userFegin.getUserById(userId);

        order.setUser(user);

        return order;
    }

    @Override
    public List<Order> findAll() {
        List<Order> orderList = orderMapper.findAll();
        List<User> userList = userFegin.findAll();

        Map<Integer, User> userMap = new HashMap<Integer, User>();
        userList.forEach(user->{
            userMap.put(user.getId(),user);
        });
        orderList.forEach(order->{
            Integer userId = order.getUserId();
            User user = userMap.get(userId);
            order.setUser(user);
        });

        return orderList;
    }


}
